package com.api.demo.service.impl;

import com.api.demo.config.FileStorageConfig;
import com.api.demo.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Autowired
    private FileStorageConfig fileStorageConfig;

    private Path fileStorageLocation;

    @PostConstruct
    public void init() {
        this.fileStorageLocation = fileStorageConfig.getUploadPath();
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (IOException ex) {
            throw new RuntimeException("Could not create the directory where the uploaded files will be stored.", ex);
        }
    }

    @Override
    public String storeFile(MultipartFile file) {
        return storeFile(file, null);
    }

    @Override
    public String storeFile(MultipartFile file, String subDirectory) {
        // 规范化文件名
        String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
        
        // 检查文件名是否包含无效字符
        if (originalFileName.contains("..")) {
            throw new RuntimeException("Sorry! Filename contains invalid path sequence " + originalFileName);
        }

        // 生成唯一文件名
        String fileExtension = "";
        if (originalFileName.contains(".")) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID().toString() + fileExtension;
        
        Path targetLocation;
        String relativePath;
        
        if (subDirectory != null && !subDirectory.isEmpty()) {
            Path subDirectoryPath = this.fileStorageLocation.resolve(subDirectory);
            try {
                Files.createDirectories(subDirectoryPath);
            } catch (IOException ex) {
                throw new RuntimeException("Could not create the subdirectory.", ex);
            }
            targetLocation = subDirectoryPath.resolve(fileName);
            relativePath = subDirectory + "/" + fileName;
        } else {
            targetLocation = this.fileStorageLocation.resolve(fileName);
            relativePath = fileName;
        }

        try {
            // 复制文件到目标位置
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            
            // 返回文件的URL
            return fileStorageConfig.getUrlPrefix() + relativePath;
        } catch (IOException ex) {
            throw new RuntimeException("Could not store file " + fileName + ". Please try again!", ex);
        }
    }
} 